package com.ruoyi.web.controller.topic;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.ruoyi.common.config.CosConfig;
import com.ruoyi.common.config.lphCosConfig;
import com.ruoyi.system.domain.Article;
import com.ruoyi.system.domain.Myuser;
import com.ruoyi.system.domain.User;
import com.ruoyi.system.domain.ZhyCollect;
import com.ruoyi.system.domain.vo.FirstPageArticle;
import com.ruoyi.system.domain.vo.Result;
import com.ruoyi.system.domain.vo.Results;
import com.ruoyi.system.domain.vo.ShowArticle;
import com.ruoyi.system.service.ArticleService;
import com.ruoyi.system.service.TypeService;
import com.ruoyi.system.service.ZhyCollectService;
import com.ruoyi.web.controller.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Api(tags = "话题模块")
@RestController
@RequestMapping("/api")
public class ArticleController extends BaseController {
    @Autowired
    private ZhyCollectService zhyCollectService;
    @Autowired
    private ArticleService articleService;

    @Autowired
    private TypeService typeService;

    @GetMapping("/articles")
    @ApiOperation("后台查看所有话题")
    public Result<List<Article>> getArticleList(){
        return Result.success(articleService.getAllArticles());
    }

    @GetMapping("/articles/articleId/{articleId}")
    @ApiImplicitParam(name = "articleId", value = "话题id", required = true, dataType = "Integer",dataTypeClass = Integer.class)
    @ApiOperation("根据id查询话题")
    public Result<FirstPageArticle> getArticleById(@PathVariable("articleId") Long id){
        /*ShowArticle articleById = articleService.getArticleById(id);*/
        return Result.success(articleService.getArticleById(id));
    }
    @GetMapping("/articles/ByUserid/{userid}")
    @ApiImplicitParam(name = "userid", value = "用户id", required = true, dataType = "Integer",dataTypeClass = Integer.class)
    @ApiOperation("根据id查询话题")
    public Result<List<FirstPageArticle>> getArticleByuserId(@PathVariable("userid") Long id){
        /*ShowArticle articleById = articleService.getArticleById(id);*/
        return Result.success(articleService.getArticleTagByUserId(id));
    }

    @ApiOperation("新增话题")
    @PostMapping("/articles/input")
    public Results addArticles(@RequestParam("userId") Integer userId,@RequestParam("typeId") Integer  typeId,@RequestParam("tagId") Integer tagId,@RequestParam("title") String title,@RequestParam("content") String content,@RequestParam("description") String description,@RequestParam("imageFile") MultipartFile image ){
        /*article.setUser((User) session.getAttribute("user"));*/
        /*article.setType(typeService.getTypeById(article.getType().getId()));
        article.setTypeId(article.getType().getId());*/
        /*article.setUserId(article.getUser().getId());*/
        Article article = new Article();
        article.setUserId(userId.longValue());
        article.setTagId(tagId.longValue());
        article.setTypeId(typeId.longValue());
        article.setContent(content);
        article.setDescription(description);
        article.setTitle(title);
        String originalFilename = image.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            COSClient cosClient = new lphCosConfig().cosClient();
            String url=null;
            String newfilename= UUID.randomUUID().toString()+suffix;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            try {
                InputStream inputStream = image.getInputStream();
                objectMetadata.setContentLength(inputStream.available());
                PutObjectRequest putObjectRequest1 = new PutObjectRequest(new lphCosConfig().getbucket(),newfilename, inputStream, objectMetadata);
                cosClient.putObject(putObjectRequest1);
                url = "https://" + new lphCosConfig().getbucket() + ".cos.ap-guangzhou.myqcloud.com" + "/" +newfilename;
                article.setFirstPicture(url);
                articleService.saveArticle(article);
                return new Results(400,"",null);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                cosClient.shutdown();
            }
        return new Results(403,"上传失败","");
    }

    @ApiOperation("修改话题")
    @PostMapping("/articles/update")
    public Result<?> updateArticles(@RequestParam("id") Long id,@RequestParam("title")String title,@RequestParam("content") String content,
                                    @RequestParam("tagId") Long tagId,@RequestParam("typeId") Long typeId,@RequestParam("description") String description,
                                    @RequestParam(value = "FirstPicture",required=false) MultipartFile FirstPicture){
        FirstPageArticle articleById = articleService.getArticleById(id);
        ShowArticle showArticle = new ShowArticle();
        showArticle.setContent(content);
        showArticle.setId(id);
        showArticle.setTypeId(typeId);
        showArticle.setTagId(tagId);
        showArticle.setDescription(description);
        showArticle.setTitle(title);
        showArticle.setFirstPicture(articleById.getFirstPicture());
        if(FirstPicture==null){
            return Result.success(articleService.updateArticle(showArticle));
        }else {
            String originalFilename = FirstPicture.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            COSClient cosClient = new lphCosConfig().cosClient();
            String url = null;
            String newfilename = UUID.randomUUID().toString() + suffix;
            ObjectMetadata objectMetadata = new ObjectMetadata();
            try {
                String key = (articleById.getFirstPicture()).substring((articleById.getFirstPicture()).lastIndexOf("/"));
                cosClient.deleteObject(new lphCosConfig().getbucket(), key);
                InputStream inputStream = FirstPicture.getInputStream();
                objectMetadata.setContentLength(inputStream.available());
                PutObjectRequest putObjectRequest1 = new PutObjectRequest(new lphCosConfig().getbucket(), newfilename, inputStream, objectMetadata);
                cosClient.putObject(putObjectRequest1);
                url = "https://" + new lphCosConfig().getbucket() + ".cos.ap-guangzhou.myqcloud.com" + "/" + newfilename;
                showArticle.setFirstPicture(url);
                return Result.success(articleService.updateArticle(showArticle));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cosClient.shutdown();
            }
        }
        return Result.fail("修改失败!");
    }

    @ApiOperation("删除话题")
    @GetMapping("/articles/delete/{id}")
    public Result<?> deleteArticles(@PathVariable("id")Integer id){
        FirstPageArticle articleById = articleService.getArticleById(id.longValue());
        String firstPicture = articleById.getFirstPicture();
        COSClient cosClient = new lphCosConfig().cosClient();
        String key=(firstPicture).substring((firstPicture).lastIndexOf("/"));
        try {
            cosClient.deleteObject(new lphCosConfig().getbucket(),key);
            ZhyCollect zhyCollect = new ZhyCollect();
            zhyCollect.setType("话题");
            zhyCollect.setId(id);
            zhyCollectService.deleteCollectById(zhyCollect);
        } catch (CosClientException e) {
            return Result.fail("删除失败");
        } finally {
            cosClient.shutdown();
        }
        articleService.deleteArticle(id.longValue());
        return Result.success();
    }


}
